import threading
import os
import cv2
import numpy as np

# 手动输入标定参数
mtx = np.array([[614.854768244664, 0, 653.981854558733],    # 内参矩阵 [[fx, 0, cx],
               [0, 615.756527830237, 376.355535849430],    #         [0, fy, cy],
               [0, 0, 1]])            #         [0, 0, 1]]
               
dist = np.array([-0.319279813720085, 0.103367999432610, 0, 0, 0])  # 畸变系数 [k1,k2,p1,p2,k3]


class FrameManager:
    def __init__(self):
        self.current_frame = None
        self.is_running = False
        self.camera_cap = None
        self.thread = None
        self.frame_lock = threading.Lock()
    
    def start_camera(self, camera_id=0):
        self.camera_cap = cv2.VideoCapture(camera_id)
        if not self.camera_cap.isOpened():
            return False
        self.is_running = True
        self.thread = threading.Thread(target=self._capture_frames, daemon=True)
        self.thread.start()
        return True
    
    def _capture_frames(self):
        while self.is_running:
            ret, frame = self.camera_cap.read()
            if ret:
                frame=cv2.flip(frame,1)
                frame=cv2.undistort(frame, mtx, dist)
                frame=cv2.resize(frame,(640,480))
                with self.frame_lock:
                    self.current_frame = frame  # 更新帧
    
    def get_current_frame(self):
        with self.frame_lock:
            return self.current_frame.copy() if self.current_frame is not None else None
    
    def stop_camera(self):
        self.is_running = False
        if self.camera_cap:
            self.camera_cap.release()